package com.julis.download;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

/**
 * 将下载方法封装在此类 提供下载，暂停，删除，以及重置的方法
 */
public class DownloadUtil {

	private DownloadHttpTool mDownloadHttpTool;
	private OnDownloadListener onDownloadListener;

	private int fileSize;
	private int downloadedSize = 0;
//	private int downLoadedSize[] = new int[5];

	/**
	 * 下载失败结果回调
	 */
	public static int ERROR_DOWNLOAD = 100;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == ERROR_DOWNLOAD) {
				onDownloadListener.downloadError(-1, "下载失败", (Exception)msg.obj);
			} else {
//				downLoadedSize[msg.what] = msg.arg1;
				int length = msg.arg1;
				synchronized (this) {// 加锁保证已下载的正确性
					downloadedSize += length;
//					for (int len : downLoadedSize) {
//						downloadedSize += len;
//					}
				}
				if (onDownloadListener != null) {
					onDownloadListener.downloadProgress(downloadedSize);
				}
				if (downloadedSize >= fileSize) {
					mDownloadHttpTool.compelete();
					if (onDownloadListener != null) {
						onDownloadListener.downloadEnd();
					}
				}
			}

		}

	};

	public DownloadUtil(String urlString, String filePath, String filename,
						int threadCount, Context context) {

		mDownloadHttpTool = new DownloadHttpTool(urlString, filePath, filename,
				threadCount, context, mHandler);
	}

	// 下载之前首先异步线程调用ready方法获得文件大小信息，之后调用开始方法
	public void start() {
		new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... arg0) {
				mDownloadHttpTool.ready();
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				fileSize = mDownloadHttpTool.getFileSize();
				downloadedSize = mDownloadHttpTool.getCompeleteSize();
				// Log.w("Tag", "downloadedSize::" + downloadedSize);
				if (onDownloadListener != null) {
					onDownloadListener.downloadStart(fileSize);
				}
				mDownloadHttpTool.start(mHandler);
			}
		}.execute();
	}

	public void pause() {
		mDownloadHttpTool.pause();
	}

	public void delete() {
		mDownloadHttpTool.delete();
	}

	public void reset() {
		mDownloadHttpTool.delete();
		start();
	}

	public void setOnDownloadListener(OnDownloadListener onDownloadListener) {
		this.onDownloadListener = onDownloadListener;
	}

	// 下载回调接口
	public interface OnDownloadListener {
		public void downloadStart(int fileSize);

		public void downloadProgress(int downloadedSize);

		public void downloadEnd();

		public void downloadError(int code, String message, Exception e);
	}
}